import tkinter as tk
from tkinter import messagebox, ttk
from datetime import datetime
import re

class MainApplication:
    def __init__(self,queue,happy_submit_event,sport_submit_event):
        self.queue = queue
        self.happy_submit_event = happy_submit_event
        self.sport_submit_event = sport_submit_event

        self.root = tk.Tk()
        self.root.title("达达记录")
        self.root.geometry("400x470")
        self.root.configure(bg="#87CEEB")

        # 创建容器框架
        self.container = tk.Frame(self.root, bg="#87CEEB")
        self.container.pack(fill="both", expand=True)

        # 初始化页面
        self.frames = {}
        for Page in (HappyRecordPage, SportRecordPage):
            if Page == HappyRecordPage:
                frame = Page(self.container, self,self.queue,self.happy_submit_event)
            if Page == SportRecordPage:
                frame = Page(self.container, self,self.queue,self.sport_submit_event)
            self.frames[Page] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(HappyRecordPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def run(self):
        self.root.mainloop()

class BasePage(tk.Frame):
    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller
        self.theme_color = "#87CEEB"
        self.button_color = {"submit": "#0099CC", "reset": "#666666", "switch": "#FF9933"}
        self.font = ("微软雅黑", 10)
        self.data = {}

class HappyRecordPage(BasePage):
    def __init__(self, parent, controller,queue,submit_event):
        super().__init__(parent, controller)
        self.queue = queue
        self.submit_event = submit_event

        self.configure(bg=self.theme_color)
        
        self.create_widgets()
        self.setup_layout()
        
    def create_widgets(self):
        # 设备记录页面控件
        self.main_frame = tk.Frame(self, bg=self.theme_color, padx=20, pady=20)
        self.main_frame.pack(expand=True, fill=tk.BOTH)

        # 日期输入
        self.date_label = tk.Label(self.main_frame, text="日期（YYYY-MM-DD）：", 
                                bg=self.theme_color, font=self.font)
        self.date_entry = tk.Entry(self.main_frame, font=self.font)
        self.date_entry.insert(0, datetime.now().strftime("%Y-%m-%d"))

        # 设备状态
        self.device_label = tk.Label(self.main_frame, text="设备状态：", 
                                  bg=self.theme_color, font=self.font)
        self.device_status_var = tk.StringVar(value="未使用")
        self.device_menu = tk.OptionMenu(self.main_frame, self.device_status_var, "使用", "未使用")
        self.device_menu.config(font=self.font, bg="white")
        
        # 时长输入
        self.duration_label = tk.Label(
            self.main_frame,
            text="时长（分钟）：",
            bg=self.theme_color,
            font=self.font
        )
        self.duration_entry = tk.Entry(self.main_frame, font=self.font)
        self.duration_entry.insert(0, "00:00:00")
        
        # 位置输入
        self.location_label = tk.Label(
            self.main_frame,
            text="位置：",
            bg=self.theme_color,
            font=self.font
        )
        self.location_entry = tk.Entry(self.main_frame, font=self.font)
        
        # 场所输入
        self.place_label = tk.Label(
            self.main_frame,
            text="场所：",
            bg=self.theme_color,
            font=self.font
        )
        self.place_entry = tk.Entry(self.main_frame, font=self.font)
        
        # 按钮区域
        self.submit_btn = tk.Button(
            self.main_frame,
            text="提交数据",
            command=self.submit,
            bg=self.button_color["submit"],
            fg="white",
            font=("微软雅黑", 10, "bold"),
            relief=tk.FLAT,
            padx=10
        )
        
        self.reset_btn = tk.Button(
            self.main_frame,
            text="重置数据",
            command=self.reset_fields,
            bg=self.button_color["reset"],
            fg="white",
            font=("微软雅黑", 10, "bold"),
            relief=tk.FLAT,
            padx=10
        )

        self.switch_btn = tk.Button(
            self.main_frame,
            text="切换到运动记录",
            command=lambda: self.controller.show_frame(SportRecordPage),
            bg=self.button_color["switch"],
            fg="white",
            font=self.font
        )
        
    def setup_layout(self):
        # 表单布局
        rows = [
            (self.date_label, self.date_entry),
            (self.device_label, self.device_menu),
            (self.duration_label, self.duration_entry),
            (self.location_label, self.location_entry),
            (self.place_label, self.place_entry)
        ]

        for row, (label, entry) in enumerate(rows):
            label.grid(row=row, column=0, padx=10, pady=8, sticky=tk.E)
            entry.grid(row=row, column=1, padx=10, pady=8, sticky=tk.EW)
        
        # 列权重配置
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.columnconfigure(1, weight=3)
        
        # 按钮布局（并排显示）
        self.submit_btn.grid(
            row=len(rows), 
            column=0,
            padx=(0, 5),  # 右侧留5像素间距
            pady=20,
            sticky=tk.EW
        )
        self.reset_btn.grid(
            row=len(rows),
            column=1,
            padx=(5, 0),  # 左侧留5像素间距
            pady=20,
            sticky=tk.EW
        )
        self.switch_btn.grid(row=6, column=0, columnspan=2, pady=10, sticky=tk.EW)
        
    def reset_fields(self):
        """重置所有输入字段到初始状态"""
        self.date_entry.delete(0, tk.END)
        self.date_entry.insert(0, self.default_date)
        self.device_status_var.set(self.default_status)
        self.duration_entry.delete(0, tk.END)
        self.location_entry.delete(0, tk.END)
        self.place_entry.delete(0, tk.END)   
    def submit(self):
        data = {}
        
        # 验证日期
        date = self.date_entry.get().strip()
        try:
            datetime.strptime(date, "%Y-%m-%d")
            data['date'] = date
        except ValueError:
            messagebox.showerror("错误", "日期格式不正确，请使用YYYY-MM-DD格式")
            return
            
        # 获取设备状态
        data['device_status'] = self.device_status_var.get()
        
        # 验证时长
        duration = self.duration_entry.get().strip()
        if not duration.isdigit() or int(duration) <= 0:
            messagebox.showerror("错误", "时长必须为正整数")
            return
        data['duration'] = int(duration)
        
        # 验证位置
        location = self.location_entry.get().strip()
        if not location:
            messagebox.showerror("错误", "位置不能为空")
            return
        data['location'] = location
        
        # 验证场所
        place = self.place_entry.get().strip()
        if not place:
            messagebox.showerror("错误", "场所不能为空")
            return
        data['place'] = place
        
        # 显示结果
        messagebox.showinfo("提交成功", "数据已保存！")
        print("保存的数据：", data)
        self.queue.put(data)
        self.submit_event.set()
        
    def run(self):
        self.root.mainloop()

    def get_data(self):
        return self.data
    

class SportRecordPage(BasePage):
    def __init__(self, parent, controller,queue,submit_event):
        self.queue = queue
        self.submit_event = submit_event

        super().__init__(parent, controller)
        self.configure(bg=self.theme_color)
        self.create_widgets()
        self.setup_layout()

    def create_widgets(self):
        self.main_frame = tk.Frame(self, bg=self.theme_color, padx=20, pady=20)
        self.main_frame.pack(expand=True, fill=tk.BOTH)

        # 运动时长输入
        fields = [
            ("运动类型","sport",""),
            ("运动地点","location",""),
            ("运动场地","place",""),
            ("日期", "date", datetime.now().strftime("%Y-%m-%d")),
            ("路程（公里）", "distance", "0.0"),
            ("运动时长(HH:MM:SS)", "duration", "00:00:00"),
            ("消耗热量(大卡)", "calories", "0"),
            ("平均配速(min/km)", "avg_pace", "0.0"),
            ("平均速度(km/h)", "avg_speed", "0.0")
        ]

        self.entries = {}
        for idx, (label, field, default) in enumerate(fields):
            lbl = tk.Label(self.main_frame, text=label, bg=self.theme_color, font=self.font)
            ent = tk.Entry(self.main_frame, font=self.font)
            ent.insert(0, default)
            self.entries[field] = ent
            lbl.grid(row=idx, column=0, padx=10, pady=5, sticky=tk.E)
            ent.grid(row=idx, column=1, padx=10, pady=5, sticky=tk.EW)

        # 按钮区域
        self.submit_btn = tk.Button(
            self.main_frame,
            text="提交运动数据",
            command=self.submit,
            bg=self.button_color["submit"],
            fg="white",
            font=self.font
        )

        self.reset_btn = tk.Button(
            self.main_frame,
            text="重置数据",
            command=self.reset_fields,
            bg=self.button_color["reset"],
            fg="white",
            font=self.font
        )

        self.switch_btn = tk.Button(
            self.main_frame,
            text="切换到设备记录",
            command=lambda: self.controller.show_frame(HappyRecordPage),
            bg=self.button_color["switch"],
            fg="white",
            font=self.font
        )

    def setup_layout(self):
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.columnconfigure(1, weight=3)
        
        # 按钮布局
        self.submit_btn.grid(row=9, column=0, padx=5, pady=10, sticky=tk.EW)
        self.reset_btn.grid(row=9, column=1, padx=5, pady=10, sticky=tk.EW)
        self.switch_btn.grid(row=10, column=0, columnspan=2, pady=10, sticky=tk.EW)

    def validate_duration(self, duration):
        pattern = r"^([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$"
        return re.match(pattern, duration)

    def submit(self):
        data = {}

        data["sport"] = self.entries["sport"].get()
        data["location"] = self.entries["location"].get()
        data["place"] = self.entries["place"].get()
        
        # 日期验证
        try:
            datetime.strptime(self.entries["date"].get(), "%Y-%m-%d")
            data["date"] = self.entries["date"].get()
        except ValueError:
            messagebox.showerror("错误", "无效的日期格式")
            return

        # 运动时长验证
        if not self.validate_duration(self.entries["duration"].get()):
            messagebox.showerror("错误", "时长格式应为HH:MM:SS")
            return
        data["duration"] = self.entries["duration"].get()

        # 数值字段验证
        numeric_fields = ["calories", "distance", "avg_speed", "avg_pace"]
        for field in numeric_fields:
            try:
                if field == "calories":
                    data[field] = int(self.entries[field].get())
                else:
                    data[field] = float(self.entries[field].get())
            except ValueError:
                messagebox.showerror("错误", f"{field} 必须为有效数字")
                return

        # 其他字段
        

        self.data = data
        messagebox.showinfo("成功", "运动数据已保存！")
        print("运动数据：", data)
        self.queue.put(data)
        self.submit_event.set()

    def reset_fields(self):
        for field, entry in self.entries.items():
            entry.delete(0, tk.END)
            if field == "date":
                entry.insert(0, datetime.now().strftime("%Y-%m-%d"))
            elif field == "duration":
                entry.insert(0, "00:00:00")
            else:
                entry.insert(0, "0" if field == "calories" else "0.0")




if __name__ == "__main__":
    app = HappyRecordPage()
    app.run()